<?php
namespace Usap\Service\CMS;

use Think\Cache;
class advert{
	
	
	
	/**
	 * 删除图片缓存
	 * @param unknown $cache_key
	 */
	public function clearImgCache($part_id){

        $key = empty($part_id) ? 'advert:*' : "advert:{$part_id}:*";
		
		
		$cache_obj = Cache::singleton('redis');
		$key_list = $cache_obj->keys($key);
		if($key_list){
			
			foreach($key_list as $cache_key){
				
				$cache_obj->del($cache_key);
			}
		}
	}
	
	

	
	/**
	 * 设置缓存内容
	 * @param unknown $cache_key
	 * @param unknown $cache_content
	 */
	public function setImgCache($cache_key,$cache_content){
		
		if(empty($cache_key) || empty($cache_content)) return ;
		
		$cache_obj = Cache::singleton('redis');

		$cache_obj->set($cache_key, $cache_content, 60*60);//缓存1小时
	}
	
	
	/**
	 * 获取图片缓存
	 * @param unknown $cache_key
	 */
	public function getImgCache($cache_key){
		
		if(empty($cache_key)) return ;
		
		$cache_obj = Cache::singleton('redis');
		
		$cache_obj->get($cache_key);//缓存1小时
	}
	
	
	
	
	/**
	 * 删除广告位图片
	 * @param unknown $img_type
	 * @param unknown $posotion_type
	 * @param unknown $position_id
	 */
	public function removeImgInfoByType($img_type ,$position_type='', $position_id='', $part_id = 0){

		$where_case = "img_type='$img_type'";
		if(!empty($position_type))
			$where_case .= ' AND  position_type='.$position_type;
		
		if(!empty($position_id))
			$where_case .= ' AND  position_id='.$position_id;

        if(!empty($part_id))
            $where_case .= ' AND  part_id='.$part_id;

		$count = D("Usap/Account/AdvertImage")->where($where_case)->count();
		if(!$count){

			return array('code'=>'-1001','msg'=>'指定广告图片不存在');
		}

		//删除图片
		$record_info = D("Usap/Account/AdvertImage")->where($where_case)->select();
//		foreach ($record_info as $record){
//			if($record['img_url']){
//				$img_path = UPLOAD_PATH.$image_url;
//				$deal_result = unlink($img_path);
//			}
//		}
// 		$image_url = $record_info['img_url'];
		
// 		if($image_url){

// 			$img_path = UPLOAD_PATH.$image_url;
// 			$deal_result = unlink($img_path);
// 			if($deal_result === false){

// 				return array('code'=>'-1001','msg'=>'图片删除失败');
// 			}
// 		}

		//删除记录
		$remove_result =  D("Usap/Account/AdvertImage")->where($where_case)->delete();
		$this->clearImgCache($part_id);
		if($remove_result!=false){
			
			return array('code'=>'-1001','msg'=>'记录删除失败');
		}
		
		return array('code'=>'0000','msg'=>'删除成功');
		
	}
	
	/**
	 * 通过图片类型＋位置类型 同步图片信息
	 * @param unknown $img_type			图片类型
	 * @param unknown $position_type	位置类型
	 * @param unknown $postion_id		位置ID
	 * @param unknown $sync_info		图片同步信息
	 */
	public function syncImgInfoByType($img_type, $position_type, $postion_id, $sync_info, $part_id = 0){

		$where_case = "img_type='$img_type' AND  position_type='$position_type' AND position_id='$postion_id' AND part_id='$part_id'";
		$count = D("Usap/Account/AdvertImage")->where($where_case)->count();
		
		$sync_data = array(
			'title'=>$sync_info['title'],
			'img_url'=>$sync_info['img_url'],
			'link_url'=>$sync_info['link_url'],
            'app_url' => $sync_info['app_url'],
            'app_url_type' => $sync_info['app_url_type'],
			'is_top'=>$sync_info['is_top']>0 ? $sync_info['is_top'] : 0,
			'is_pub'=>$sync_info['is_pub']>0 ? $sync_info['is_pub'] : 0,
			'list_order'=>$sync_info['list_order']>0 ? $sync_info['list_order'] : 0,
		);
		if($count>0){//更新

			$sync_data['update_time'] = date('Y-m-d H:i:s');
			$opt_result =  D("Usap/Account/AdvertImage")->where($where_case)->data($sync_data)->save();
		}else{//插入
			$sync_data['img_type'] = $img_type;
			$sync_data['position_type'] = $position_type;
			$sync_data['position_id'] = $postion_id;
            $sync_data['part_id'] = $part_id;
			$sync_data['create_time'] = date('Y-m-d H:i:s');
			$opt_result = D("Usap/Account/AdvertImage")->add($sync_data);
		}

        \Logger::getLogger('wifi1.0.Service.CMS.advent')->apps('syncImgInfoByType')->info(
            array(
                'title' => '图片信息修改',
                'img_type' => $img_type,
                'sync_info' => $sync_info,
                'sql' => D("Usap/Account/AdvertImage")->_sql(),
                'res' => $opt_result
            )
        );
		
		
		$this->clearImgCache($part_id);
		
		return $opt_result;
	}
	
	/**
	 * 获取图片列表
	 * @param string $img_type	图片类型
	 * 		登录前portal:grant
	 *  	登录等待页:online
	 *  	登录后portal:aftergrant
	 *  
	 *  @return array(
	 *  	'total'=>记录总数
	 *  	'list'=>记录数列表
	 *  );
	 */
	public function getImgListByType($img_type,$postion_type, $part_id = 0){

		$return_info = array('total'=>0,'list'=>array());//返回值列表
		
		if(empty($img_type)){

			return $return_info;
		}

		/*从缓存中获取地址*/
		$args_str = var_export(func_get_args(),true);
		$cache_key = !empty($part_id) ? "advert:{$part_id}:".md5($args_str) : 'advert:'.md5($args_str);

		$cache_list = $this->getImgCache($cache_key);
		if(!empty($cache_list)){

			return $cache_list;
		}
		
		
		$count = D("Usap/Account/AdvertImage")->where("img_type='$img_type' AND position_type='$postion_type' AND part_id='$part_id'")->count();
		if(!$count){
			
			return $return_info;
		}
		$return_info['total'] = $count;
		$return_info['list'] = array();//初始化列表
		
		$data_list = D("Usap/Account/AdvertImage")->where("img_type='$img_type' AND position_type='$postion_type' AND is_pub='1' AND part_id='$part_id'")->order("list_order ASC,is_top DESC")->select();
		foreach($data_list as $key=>&$value){

			if($value['list_order']=='0'){
				$value['list_order'] = '';
			}
// 			$img_level = $value['img_level'];//图片深度
			$img_type = $value['img_type'];//图片类型
			$position_id = $value['position_id'];//图片位置ID
			
			$return_info['list'][$position_id] = $value;
		}
		
		$this->setImgCache($cache_key, $return_info);
		return $return_info;
	}

    /**
     * 随机 获取广告图片
     *
     * @param $img_type 图片类型
     * @param $position_type 广告 位置
     * @param string $part_id 区域id
     * @param int $limit 个数
     * @return array
     */
    public function getRandAdvert($img_type, $position_type, $part_id = '', $limit = 1)
    {
        $img_info = $this->getImgListByType($img_type, $position_type, $part_id);

        $res_advert_info = array();
        if(!$img_info['total']){ return $res_advert_info; }
        $limit < $img_info['total'] ?: $limit = $img_info['total'];

        $rand_num = array();
        $i = 0;
        while($i < $limit){
            $count_num = mt_rand(1, $img_info['total']);
            if(!in_array($count_num, $rand_num)){
                $rand_num[] = $count_num;
                $res_advert_info[] = $img_info['list'][$count_num];
                $i++;
            }
        }

        return $res_advert_info;
    }

}
